<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search">
      <!-- 表单组件 -->
      <el-form
        :inline="true"
        ref="searchFromRef"
        :model="om"
        class="searchForm"
      >
        <!-- 表单项 -->
        <el-form-item label="订单号:" style="width: 200px" prop="orderNo">
          <el-input placeholder="请输入订单号" v-model="om.orderNo" />
        </el-form-item>
        <!-- 表单项 -->
        <el-form-item
          label="支付状态:"
          style="width: 200px; margin-left: 10px"
          prop="payStatus"
        >
          <el-select v-model="om.payStatus" placeholder="请选择状态">
            <el-option label="未支付" value="0" />
            <el-option label="支付成功" value="1" />
          </el-select>
        </el-form-item>

        <!-- 表单项 -->
        <el-form-item
          label="订单状态:"
          style="width: 200px; margin-left: 10px"
          prop="orderStatus"
        >
          <el-select v-model="om.orderStatus" placeholder="请选择订单状态">
            <el-option label="待支付" value="0" />
            <el-option label="已支付" value="1" />
            <el-option label="配货完成" value="2" />
            <el-option label="出库成功" value="3" />
            <el-option label="交易完成" value="4" />
            <el-option label="手动关闭" value="-1" />
            <el-option label="超时关闭" value="-2" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button
        color="#909399"
        plain
        :icon="Search"
        @click="search"
        style="width: 75px"
        >查询</el-button
      >
      <el-button
        color="#e6a23c"
        plain
        :icon="Refresh"
        @click="resetSearch"
        style="width: 75px"
        >重置</el-button
      >
    </div>

    <!-- 操作区 -->
    <div class="action">
      <el-button
        type="danger"
        plain
        :icon="Delete"
        @click="deleteAll"
        style="margin-left: 10px"
        >批量删除</el-button
      >
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 表格 -->
      <div class="grid">
        <el-table
          :data="tableData"
          style="width: 100%"
          :header-cell-style="headerCellStyle"
          @row-click="rowClick"
          ref="tableRef"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="orderId"
            label="订单ID"
            width="100"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="orderNo"
            label="订单号"
            width="200"
            align="center"
            header-align="center"
          />
          <el-table-column
            prop="user.loginName"
            label="用户名"
            width="120"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="orderItem[0].goodsName"
            label="商品名称"
            width="200"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            prop="totalPrice"
            label="订单总价"
            width="120"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="payStatus"
            label="支付状态"
            width="120"
            align="center"
            header-align="center"
            :formatter="(row) => (row.payStatus === 1 ? '已支付' : '未支付')"
          />

          <el-table-column
            prop="orderStatus"
            label="订单状态"
            width="150"
            align="center"
            header-align="center"
            :formatter="
              (row) => {
                switch (row.orderStatus) {
                  case 0:
                    return '待支付';
                  case 1:
                    return '已支付';
                  case 2:
                    return '配货完成';
                  case 3:
                    return '出库成功';
                  case 4:
                    return '交易成功';
                  case -1:
                    return '手动关闭';
                  case -2:
                    return '超时关闭';
                  case -3:
                    return '商家关闭';
                  default:
                    return '未知状态';
                }
              }
            "
          />
          prop="payTime" label="支付时间" width="180" align="center"
          header-align="center" />

          <el-table-column
            prop="createTime"
            label="创建时间"
            width="200"
            align="center"
            header-align="center"
          />

          <el-table-column
            prop="extraInfo"
            label="订单额外信息"
            width="150"
            align="center"
            header-align="center"
          />

          <el-table-column fixed="right" label="操作" min-width="360px">
            <template #default="scope">
              <el-button
                type="warning"
                :icon="Edit"
                style="width: 90px"
                @click="lookOrder(scope.row)"
                plain
                >订单详情
                </el-button
              >
              <el-dropdown
                split-button
                type="success"
                plain 
                style="margin-left: 10px"
                @click="handleCommand('edit', scope.row)"
              >
                操作
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      :icon="Edit"
                      @click.native="handleCommand('editMesById', scope.row)"
                      >备注</el-dropdown-item
                    >
                    <el-dropdown-item
                      :icon="Edit"
                      @click.native="handleCommand('edit', scope.row)"
                      >修改</el-dropdown-item
                    >
                    <el-dropdown-item
                      :icon="Delete"
                      @click.native="handleCommand('removeById', scope.row)"
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <!-- <el-button
                type="success"
                plain
                :icon="Edit"
                @click="EditMesById(scope.row)"
                style="width: 60px"
                >备注</el-button
              >
              <el-button
                color="#409eff"
                :icon="Edit"
                style="width: 60px"
                @click="edit(scope.row)"
                plain
                >修改</el-button
              >
              <el-button
                type="danger"
                plain
                :icon="Delete"
                @click="removeById(scope.row)"
                style="width: 60px"
                >删除</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-pageNum="pageInfo.pageNum"
          v-model:pageNum-size="pageInfo.size"
          :pageNum-sizes="[10, 15, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          background
          @change="paginate"
        />
      </div>
    </div>
  </div>

  <!-- 新增 对话框 -->
  <el-dialog
    v-model="show"
    :title="title"
    width="500"
    draggable
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form ref="sfRef" :model="ofm">
      <el-form-item
        label="订单号:"
        label-width="100"
        prop="orderNo"
        style="width: 80%"
      >
        <el-input v-model="ofm.orderNo" readonly />
      </el-form-item>

      <el-form-item
        label="订单状态:"
        label-width="100"
        prop="orderStatus"
        style="width: 80%"
      >
        <el-select v-model="ofm.orderStatus" placeholder="请选择订单状态">
          <el-option label="待支付" :value="0" />
          <el-option label="已支付" :value="1" />
          <el-option label="配货完成" :value="2" />
          <el-option label="出库成功" :value="3" />
          <el-option label="交易完成" :value="4" />
          <el-option label="手动关闭" :value="-1" />
          <el-option label="超时关闭" :value="-2" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-form-item
      label="商品价格:"
      label-width="100"
      prop="totalPrice"
      style="width: 80%"
    >
      <el-input v-model="ofm.totalPrice" />
    </el-form-item>

    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 备注订单对话框 -->
  <el-dialog
    ref="sfRef"
    v-model="editVisible"
    title="订单备注"
    width="500"
    draggable
    :close-on-click-modal="false"
  >
    <el-form ref="sfRef" :model="ofm">
      <el-form-item
        label="订单号:"
        label-width="100"
        prop="orderNo"
        style="width: 80%"
      >
        <el-input v-model="ofm.orderNo" readonly />
      </el-form-item>
      <el-form-item label="订单备注" :label-width="100">
        <el-input
          type="textarea"
          v-model="ofm.extraInfo"
          placeholder="请输入订单备注"
          style="width: 75%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="margin-top: 10px" @close="close">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
  
  <script setup>
import orderApi from "@/api/OrderApi";
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";
const router = useRouter();
//修改信息对话框
const editVisible = ref(false);

// 关闭对话框，重置表单
function EditMesById(row) {
  let order = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, order);
  editVisible.value = true;
  // 下一个时间滴答中赋值
  nextTick(() => {
    ofm.value = row; //给新增/修改表单赋值
  });
}

function handleEdit() {
  let order = ofm.value;
  orderApi.update(order).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  editVisible.value = false;
}
// 下拉框“操作”执行
function handleCommand(command, row) {
      switch (command) {
        case 'editMesById':
          this.EditMesById(row);
          break;
        case 'edit':
          this.edit(row);
          break;
        case 'removeById':
          this.removeById(row);
          break;
        default:
          break;
      }
}

//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});

//响应式对象
const tableData = ref([]);

const orderItem = ref([]);
function paginate() {
  search();
}

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});

// 当页码和页码大小改变时触发

function search() {
  let params = om.value; //查询条件
  orderApi
    .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
    .then((result) => {
      if (result.code == 0) {
        console.log(result.data.list);
        tableData.value = result.data.list;
        orderItem.value = result.data.list.orderItem;
        pageInfo.value.total = result.data.total;
        pageInfo.value.pageNum = result.data.pageNo;
        pageInfo.value.size = result.data.pageSize;
      }
    });
}

// 搜索条表单双向数据绑定
const om = ref({
  orderNo: "",
  payStatus: "",
  orderStatus: "",
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}

// 删除操作逻辑
function deleteAll() {
  // 从表格中选中的行
  let rows = tableRef.getSelectionRows();
  let ids = []; //id数组
  for (let row of rows) {
    ids.push(row.orderId);
  }
  //执行删除操作
  deleteById(ids);
}
//根据id数组批量删除
function deleteById(ids) {
  // 判断是否选中了要删除的记录
  if (ids.length == 0) {
    ElMessage({
      message: "请选中要删除的记录！",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确定删除选中的记录吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      orderApi
        .removeAll(ids)
        .then((resp) => {
          if (resp.code == 0) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
            search(); //刷新
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "删除操作取消",
          });
        });
    });
  }
}
//  按id删除
function removeById(row) {
  let order = toRaw(row);
  deleteById([order.orderId]);
}

// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const adminFormModel = ref({
  orderId: "",
  orderNo: "",
  totalPrice: "",
  orderStatus: "",
  extraInfo: "",
});
// 对话框内容别名
const ofm = adminFormModel;

// 对话框标题
const title = ref("新增订单");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增订单";
}
// 提交表单
function submitForm() {
  let order = ofm.value;
  if (order.orderId) {
    //修改
    submitEdit(order);
  } else {
    //新增
    submitAdd(order);
  }
}

// 新增逻辑
function submitAdd(order) {
  orderApi.save(order).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}

// 修改操作
function edit(row) {
  let order = toRaw(row);
  // 浅拷贝
  row = Object.assign({}, order);
  show.value = true;
  title.value = "修改订单";
  // 下一个时间滴答中赋值
  nextTick(() => {
    ofm.value = row; //给新增/修改表单赋值
  });
}
// 提交表单执行逻辑
function submitEdit(order) {
  orderApi.update(order).then((resp) => {
    if (resp.code == 0) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 逻辑跳转
function lookOrder(row) {
  router.push({
    name: "orderDetail", // 对应的路由名称
    params: { id: row.orderId }, // 将订单的ID作为参数传递
  });
}
</script>
  
  <style scoped>
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}


.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
  